var ReservationsArrivedTable = {
    id: "ReservationsArrivedTable",
    seItem: null,
    table: null,
    layerIndex: -1
};

function _formatter(value, row, index) {
    if (row.dealStatus == "已结账") {
        return '<span style="color: green" title="' + value + '">' + value + '</span>'
    } else {
        return '<span title="' + value + '">' + value + '</span>'
    }
}

function _formatterTime(value, row, index) {
    if (row.dealStatus === "已结账") {
        if (value != null && value !== "") {
            return "<span style='color: green'>" + value.substring(0, 19) + "</span>"
        } else {
            return "";
        }
    } else {
        if (value != null && value != "") {
            return value.substring(0, 19);
        } else {
            return "";
        }
    }
}

function _formatterTitle(value, row, index) {
    if (row.huifang === "" || row.huifang == null) {
        row.huifang = "无回访详情";
    } else {
        row.huifang = ",<b>" + "回访详情：" + row.huifang.replace(/\s{2,}/g,"");
        var reg = /,<b>/g;
        var regs = /<\/b>/g;
        row.huifang = row.huifang.replace(reg, '&#10;');
        row.huifang = row.huifang.replace(regs, ' ');
    }
    if (row.dealStatus === "已结账") {
        if (value !== null && value !== "") {
            return "<span style='color: green; cursor:pointer' title='" + row.huifang + "' >" + value.substring(0, 19) + "</span>"
        } else {
            return "";
        }
    } else {
        if (value != null && value !== "") {
            return "<span style=' cursor:pointer' title='" + row.huifang + "' >" + value.substring(0, 19) + "</span>"
        } else {
            return "";
        }
    }
}

ReservationsArrivedTable.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: '', field: 'customerSexHead ', visible: false, align: 'center', valign: 'middle'},
        {title: '预约号', field: 'reservationsNum', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '标识号', field: 'identificationNumber', align: 'center', valign: 'middle', sortable: true, width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '姓名', field: 'customerName', align: 'center', valign: 'middle', sortable: true, width: 120,
            formatter: function (value, row, index) {
                if (row.dealStatus === "已结账") {
                    return "<a href='javascript:;' style='color: green;display: flex;align-items: center;' onclick = 'ReservationsArrivedTable.reservationsArrives(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                } else {
                    return "<a href='javascript:;' style='display: flex;align-items: center;' onclick = 'ReservationsArrivedTable.reservationsArrives(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                }
            }
        },
        {title: '手机号码', field: 'customerPhone', align: 'center', valign: 'middle', sortable: true, width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: 'E看牙病历号', field: 'ekyNumber', align: 'center', valign: 'middle', sortable: true, width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '初诊门诊', field: 'arrivalStore', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '建档人', field: 'archiving', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '跟进人', field: 'follower', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '归属人', field: 'belonger', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '建档时间', field: 'filingTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '预约时间', field: 'appointmentTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTitle(value, row, index);
            }
        },
        {title: '回访状态', field: 'statuss', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '到诊时间', field: 'firstVisitDate', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '结账时间', field: 'transactionTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '一级渠道', field: 'oneChannel', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '二级渠道',field: 'twoChannel',align: 'center',valign: 'middle',sortable: true,width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '三级渠道',field: 'thrChannel',align: 'center',valign: 'middle',sortable: true,width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '回访', field: 'huifang', align: 'center', valign: 'middle', sortable: true, width: 250,
            formatter: function (value, row, index) {
                return '<span title="'+value+'">'+value+'</span>'
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow":"hidden","white-space":"nowrap","text-overflow":"ellipsis"}}
            }
        },
        {title: '性别', field: 'customerSex', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                var sexValue = value === 1 ? '男' : value === 2 ? '女' : '未知';
                if (row.dealStatus === "已结账") {
                    return "<span style='color: green'>" + sexValue + "</span>"
                } else {
                    return sexValue;
                }
            }
        },
        {title: '年龄', field: 'customerAge', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '成交状态',field: 'dealStatus',align: 'center',valign: 'middle',sortable: true,width: 110,
            formatter: function (value, row, index) {
                if (row.dealStatus === "已结账") {
                    return "<span style='color: green'>已成交</span>"
                } else {
                    return "未成交";
                }
            }
        },
        {title: '成交金额', field: 'money', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '预约病种',field: 'appointmentPayService',align: 'center',valign: 'middle',sortable: true,width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow":"hidden","white-space":"nowrap","text-overflow":"ellipsis"}}
            }
        },
        {title: '访问病种', field: 'accessDisease', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '消费项目', field: 'expenditureProject', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '初诊TC', field: 'tcName', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '关键词', field: 'keyWord', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '微信号', field: 'wechatNumber', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
    ]
    return columns;
};

ReservationsArrivedTable.search = function () {//查询预约客户列表
    ReservationsArrivedTable.table.refresh({query: ReservationsArrivedTable.formParams()});
    // ReservationsArrivedTable.tongji();
    ReservationsArrivedTable.moneyAccount();
};

ReservationsArrivedTable.formParams = function () {//新市场预约表单查询提交参数
    var queryData = {};
    queryData['arrivalStore'] = multipleSelection($('#arrivalStore').val());
    queryData['abbreviation'] = $("#abbreviation", parent.document).val();
    queryData['rechargeStore'] = $("#rechargeStore").val();  //结账门诊
    queryData['dealStatus'] = $("#dealStatus").val();  //成交状态
    queryData['department'] = $("#department").val(); //  部门
    queryData['area'] = multipleSelection($('#area').val());
    queryData['reach'] = $("#marketInputPublic", parent.document).val();  //姓名   电话   微信  预约号
    queryData['appointmentPayService'] = $("#appointmentPayService").val();  //预约项目
    queryData['archiving'] = $("#archiving").val();   //建档人
    queryData['follower'] = $("#follower").val();   //跟进人
    queryData['accessDisease'] = $("#accessDisease").val();  //访问病种
    queryData['oneChannel'] = $("#oneChannel").val();  //一级渠道
    queryData['twoChannel'] = $("#twoChannel").val();    //二级渠道
    queryData['thrChannel'] = $("#thrChannel").val();    //三级渠道
    queryData['statuss'] = multipleSelection($('#statuss').val());
    queryData['status'] = $("#status").val();   //状态
    queryData['belonger'] = $("#belonger").val();   //归属人
    queryData['startFirstVisitDate'] = $("#startFirstVisitDate").val();  //建档时间
    queryData['endFirstVisitDate'] = $("#endFirstVisitDate").val();
    queryData['startTransactionTime'] = $("#startTransactionTime").val();  //交易时间pip
    queryData['endTransactionTime'] = $("#endTransactionTime").val();
    return queryData;
};

// ReservationsArrivedTable.tongji = function () {//统计建档已到人数
//     var param1 = multipleSelection($('#arrivalStore').val());
//     var param2 = $("#department").val();   //部门
//     var param3 = $("#appointmentPayService").val(); //预约病种
//     var param4 = $("#archiving").val();  //建档人
//     var param5 = $("#follower").val();  //跟进人
//     var param6 = $("#belonger").val();  //归属人
//     var param7 = $("#accessDisease").val();  //访问病种
//     var param8 = $("#oneChannel").val();  //一级渠道
//     var param9 = $("#twoChannel").val();  //二级渠道
//     var param10 = $("#thrChannel").val();  //三级渠道
//     var param11 = multipleSelection($('#statuss').val());
//     var param12  = $("#startFirstVisitDate").val();
//     var param13 = $("#endFirstVisitDate").val();
//     var param14 = multipleSelection($('#area').val());
//     var param15 =  $("#marketInputPublic", parent.document).val();  //姓名   电话   微信  预约号
//     var param16 = $("#rechargeStore").val();  //结账门诊
//     var param17 = $("#dealStatus").val();  //成交状态
//     $.ajax({
//         type: "GET",
//         url: Feng.ctxPath + "/reservationsArrive/tongji",
//         data: {
//             param1: param1, param2: param2, param3: param3,
//             param4: param4, param5: param5, param6: param6,
//             param7: param7, param8: param8, param9: param9,
//             param10: param10, param11: param11,
//             param12: param12, param13: param13, param14: param14, param15: param15,
//             param16: param16, param17: param17
//         },
//         dataType: "json",
//         success: function (data) {
//             $("#daozhenToday").html(data[0].countNum);
//             $("#daozhenYesterday").html(data[1].countNum);
//             $("#daozhenThisWeek").html(data[2].countNum);
//             $("#daozhenMonth").html(data[3].countNum);
//             $("#daozhenLastMonth").html(data[4].countNum);
//         }
//     });
// };

ReservationsArrivedTable.moneyAccount = function () {//统计建档已到人数金额
    $.ajax({
        type: "GET",
        url: Feng.ctxPath + '/reservationsArrive/account',
        data: ReservationsArrivedTable.formParams(),
        dataType: "json",
        success: function (data) {
            $('#recordMoney').html(data.totalMoney);
        }
    })
};

var parseParam = function (param) {//把对象拼接成URL的键值对参数  param1=value1&param2=value2
    var paramStr = "";
    $.each(param, function (i) {
        paramStr += '&' + getSingleData(param, i);
    });
    return paramStr.substr(1);
};
var getSingleData = function (param, key) {
    return key + "=" + param[key];
};

ReservationsArrivedTable.check = function () { // 检查是否选中
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        ReservationsArrivedTable.seItem = selected[0];
        return true;
    }
};

ReservationsArrivedTable.reservationsExportYD = function () {//已到导出
    var param = parseParam(ReservationsArrivedTable.formParams());
    location.href = Feng.ctxPath + '/reservationsArrive/reservationsExportYD?' + param;
};

ReservationsArrivedTable.getData = function () {//片区筛选
    var area = multipleSelection($('#area').val());
    $.post(Feng.ctxPath + "/dept/getListByArea/"+area,function (data) {
        $('#arrivalStore').empty();
        for (var i = 0; i < data.length; i++) {
            $('#arrivalStore').append("<option value=" + data[i].simplename + ">" + data[i].simplename + "</option>");
        }
        $('#arrivalStore').selectpicker('refresh');
        $('#arrivalStore').selectpicker('render');
        ReservationsArrivedTable.search();
    }, "json");
};

ReservationsArrivedTable.resetSearch = function () {//重置
    $("#marketInputPublic", parent.document).val("");
    $("#archiving").val("");
    $("#follower").val("");
    $("#accessDisease").val("");
    $("#statuss").selectpicker('deselectAll');
    $("#belonger").val("");
    $("#startFirstVisitDate").val("");
    $("#endFirstVisitDate").val("");
    $("#startTransactionTime").val("");
    $("#endTransactionTime").val("");
    $("#appointmentPayService").val("");
    $("#oneChannel").val("请选择");
    $("#twoChannel").val("请选择");
    $("#thrChannel").val("请选择");
    $("#arrivalStore").selectpicker('deselectAll');
    $("#rechargeStore").val("");
    $("#dealStatus").val("");
    $("#department").val("");
    $("#area").selectpicker('deselectAll');
    ReservationsArrivedTable.search();
};


ReservationsArrivedTable.naturalDaySearch = function (obj) {
    if (obj == 1) {
        $("#startFirstVisitDate").val(setDateTime(new Date(), 0) + " 00:00:00");
        $("#endFirstVisitDate").val(setDateTime(new Date(), 0) + " 23:59:59");
        $("#startTransactionTime").val(setDateTime(new Date(), 0) + " 00:00:00");
        $("#endTransactionTime").val(setDateTime(new Date(), 0) + " 23:59:59");
        $(".timeBox > div button").eq(0).addClass('actionClick').siblings().removeClass('actionClick')
    } else if (obj == 2) {
        var AccountsTime = $("#sttleAccountsTime").val();
        $("#startFirstVisitDate").val(setDateTime(new Date(), 1) + " " + AccountsTime);
        $("#endFirstVisitDate").val(setDateTime(new Date(), 0) + " " + AccountsTime);
        $("#startTransactionTime").val(setDateTime(new Date(), 1) + " " + AccountsTime);
        $("#endTransactionTime").val(setDateTime(new Date(), 0) + " " + AccountsTime);
        $(".timeBox > div button").eq(1).addClass('actionClick').siblings().removeClass('actionClick')
    };
    ReservationsArrivedTable.search();
};


ReservationsArrivedTable.getArchiving = function () { // 选择建档人
    var index = layer.open({
        type: 2,
        title: '选中建档人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservation/to_archiving'
    });
    this.layerIndex = index;
};

ReservationsArrivedTable.getFollower = function () {  // 选择跟进人
    var index = layer.open({
        type: 2,
        title: '添加跟进人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservations/to_follower'
    });
    this.layerIndex = index;
};

ReservationsArrivedTable.getBelonger = function () { // 选择归属人
    var index = layer.open({
        type: 2,
        title: '添加归属人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservations/to_belonger'
    });
    this.layerIndex = index;
};

ReservationsArrivedTable.reservationsArrives = function (id) {//点击表格姓名进入详情 - 已到
    var index = layer.open({
        type: 2,
        title: '到店客户详情',
        area: ['60%', '100%'], //宽高
        fix: true, //不固定
        maxmin: true,
        offset: ['0px', '40%'],
        content: Feng.ctxPath + '/reservationsArrive/reservations_arrives/' + id
    });
    this.layerIndex = index;
};

ReservationsArrivedTable.updateAccessDisease = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '修改病种',
            area: ['50%', '60%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/reservationsArrive/update_accessDisease/' + ReservationsArrivedTable.seItem.id
        });
        this.layerIndex = index
    }
};

ReservationsArrivedTable.today = function () {//点击上面状态筛选表格
    $("#startFirstVisitDate").val(setDateTime(new Date(),0) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setDateTime(new Date(),0) + " " + "23:59:59");
    ReservationsArrivedTable.search();
};

ReservationsArrivedTable.yesterday = function () {
    $("#startFirstVisitDate").val(setDateTime(new Date(),1) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setDateTime(new Date(),1) + " " + "23:59:59");
    ReservationsArrivedTable.search();
};

ReservationsArrivedTable.thisWeek = function () {
    var date = new Date();
    var currentWeek = date.getDay();
    var stepSunDay = -currentWeek + 1;
    if (currentWeek == 0) {stepSunDay = -7;}
    var stepMonday = 7 - currentWeek;
    var time = date.getTime();
    var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
    var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
    $("#startFirstVisitDate").val(setDateTime(monday,0) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setDateTime(sunday,0) + " " + "23:59:59");
    ReservationsArrivedTable.search();
};

ReservationsArrivedTable.thisMonth = function () {
    $("#startFirstVisitDate").val(firstMonthTime(new Date(),0) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setMonthTime(new Date(),0) + " " + "23:59:59");
    ReservationsArrivedTable.search();
};

ReservationsArrivedTable.lastMonth = function () {
    $("#startFirstVisitDate").val(firstMonthTime(new Date(),1) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setMonthTime(new Date(),1) + " " + "23:59:59");
    ReservationsArrivedTable.search();
};

$("#marketSearchAll", parent.document).click(function(){ // 主页搜索
    ReservationsArrivedTable.search();
});

function phonePrivileges(){   //隐藏手机号
    var phonePrivileges=parent.$("#phonePrivileges").val();
    if(phonePrivileges == 2){
        $('#ReservationsArrivedTable').bootstrapTable('hideColumn', 'customerPhone');
    }
}
var scollPostion = 0;
ReservationsArrivedTable.getScrollPosition = function (){ // 获取表格滚动到什么地方
    scollPostion = $('#ReservationsArrivedTable').bootstrapTable('getScrollPosition');
};

ReservationsArrivedTable.scrollTo = function (){ // 指定表格滚动到什么地方
    $("#ReservationsArrivedTable").on('load-success.bs.table',function(data){
        $('#ReservationsArrivedTable').bootstrapTable('scrollTo', scollPostion);
    });
};

$(function () {
    var defaultColunms = ReservationsArrivedTable.initColumn();
    var table = new BSTable(ReservationsArrivedTable.id, "/reservationsArrive/listYD", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams(ReservationsArrivedTable.formParams());
    ReservationsArrivedTable.table = table.init();
    ReservationsArrivedTable.today();
    menuNameHideColumn($("#menuName").val(),'ReservationsArrivedTable');
    $("#today").addClass('actionClick').siblings().removeClass('actionClick');
    $(document).on('click','#laydate_clear,#laydate_today,#laydate_ok',function () {ReservationsArrivedTable.search()});
    $("#oneChannel").change(function () {$("#twoChannel").val('请选择');$("#thrChannel").val('请选择');ReservationsArrivedTable.search();});
    $("#twoChannel").change(function () {$("#thrChannel").val('请选择');ReservationsArrivedTable.search();});
    $("#thrChannel").change(function () {ReservationsArrivedTable.search();});
    checkDate = function () {ReservationsArrivedTable.search()};
    callbackTable = function () {ReservationsArrivedTable.search()};
    phonePrivileges();
});